package com.example.covid19.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.covid19.common.lang.Result;
import com.example.covid19.entity.Builder;
import com.example.covid19.entity.Enum.GaoDeLocationTemp;
import com.example.covid19.entity.SelectClass.builder_local;
import com.example.covid19.entity.mongodb.Location;
import com.example.covid19.mapper.BuilderMapper;
import com.example.covid19.service.BuilderService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author BaiZhengChun
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/builder")
public class BuilderController {
    @Autowired
    BuilderService builderService;
    @Autowired
    MongoTemplate mongoTemplate;
    private final BuilderMapper builderMapper;

    public BuilderController(BuilderMapper builderMapper) {
        this.builderMapper = builderMapper;
    }

    static class Point {
        double lng;
        double lat;

        public Point(double lng, double lat) {
            this.lng = lng;
            this.lat = lat;
        }

        @Override
        public String toString() {
            return "{" +
                    "lng:" + lng +
                    ", lat:" + lat +
                    '}';
        }
    }

    static List<BuilderController.Point> parsePoints(String data) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        List<BuilderController.Point> points = new ArrayList<>();
        String[] arr = objectMapper.readValue(data, String[].class);
        for (String pointStr : arr) {
            String[] pointArr = pointStr.split(",");
            double lng = Double.parseDouble(pointArr[0]);
            double lat = Double.parseDouble(pointArr[1]);
            points.add(new BuilderController.Point(lng, lat));
        }

        return points;
    }

    /**
     * 这里是将楼保存的位置信息显示在百度地图上
     * @throws Exception
     */
    @RequestMapping("/test")
    public void test() throws Exception {
        String data = "[\"124.37553,40.18385\",\"124.37433,40.18520\",\"124.36995,40.18449\",\"124.36912,40.18495\",\"124.36794,40.18415\",\"124.36740,40.18452\",\"124.36641,40.18449\",\"124.36643,40.18384\",\"124.36679,40.18378\",\"124.36673,40.18242\",\"124.36797,40.18179\",\"124.36897,40.18197\",\"124.36948,40.18163\"]";
        List<BuilderController.Point> points = parsePoints(data);
        System.out.println(points);
    }

    /**
     * 获取所有楼的信息
     * @return
     */
    @RequestMapping("/geibuildlist")
    public Result geibuildlist(){
        List<builder_local> builderLocalList = new ArrayList<>();
        builderService.list(new QueryWrapper<Builder>().orderBy(false, true, "lid"))
                .forEach(v->{
            String str = mongoTemplate.findById(v.getLocaonid(), Location.class).getGver();
            builder_local builderLocal = new builder_local();
                    builderLocal.setGver(str);
                    builderLocal.setLid(v.getLid());
                    builderLocal.setSex(v.getSex());
                    builderLocal.setBuildName(v.getBuildName());
                    builderLocal.setCout(builderMapper.getbuilderCount(v.getLid()));
                    builderLocal.setOdds(builderMapper.getodds(v.getLid()));
                    builderLocal.setSpecsum(builderMapper.getsum(v.getLid()));
                    builderLocalList.add(builderLocal);
                });
        return Result.success(200, "yes", builderLocalList);
    }
    /**
     *
     * @return 寝室管理图表的数据
     */
    @RequestMapping("/getG2list")
    public Result getG2list(){
        List<builder_local> builderLocalList = new ArrayList<>();
        builderService.list(new QueryWrapper<Builder>().orderBy(false, true, "lid"))
                .forEach(v->{
                    builder_local builderLocal = new builder_local();
                    builderLocal.setLid(v.getLid());
                    builderLocal.setBuildName(v.getBuildName());
                    builderLocal.setCout(builderMapper.getbuilderCount(v.getLid()));
                    builderLocal.setOdds(builderMapper.getodds(v.getLid()));
                    builderLocal.setSpecsum(builderMapper.getsum(v.getLid()));
                    builderLocalList.add(builderLocal);
                });
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(builderLocalList);
        return Result.success(200, "yes", builderLocalList);
    }

    /**
     *
     * @param sex
     * @return 寝室管理界面，选择寝室时的下拉框数据
     */
    @RequestMapping("/getRoBusex")
    public Result getRoBusex(@RequestParam("sex")String sex){
        List<Builder>builderList = builderService.list(new QueryWrapper<Builder>().eq("sex",sex));
        JSONArray jsonArray = new JSONArray();
        builderList.forEach(v->{
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("value",v.getLid());
            jsonObject.set("label",v.getBuildName());
            jsonArray.put(jsonObject);
        });
        return Result.success(200,"ok",jsonArray);
    }

    /**
     *
     * @param gdlocal
     * @return 将经纬度字符串解析成JSONARRAY数组
     */
    public JSONArray StrtoLocal(String gdlocal){
        JSONArray jsonArray = JSONUtil.parseArray(gdlocal);

        // 遍历JsonArray，将每个元素拆分为经度和纬度，再转换为JSONArray对象
        for (int i = 0; i < jsonArray.size(); i++) {
            String coordinateString = jsonArray.getStr(i);
            String[] parts = coordinateString.split(",");
            double lng = Double.parseDouble(parts[0]);
            double lat = Double.parseDouble(parts[1]);
            JSONArray coordArray = new JSONArray();
            coordArray.put(lng);
            coordArray.put(lat);
            jsonArray.set(i, coordArray);
        }

        return jsonArray;
    }

    /**
     *
     * @param name
     * @param sex
     * @return 添加寝室楼
     */
    @RequestMapping("/Add")
    public Result Add(@RequestParam("name")String name,@RequestParam("sex")String sex){
        Builder builder = new Builder();
        builder.setBuildName(name);
        builder.setSex(sex);
        boolean flag = builderService.save(builder);
        if (flag){
            return Result.success(200,"ok",null);
        }else {
            return Result.fail(401,"error",null);
        }
    }

    /**
     *
     * @param id
     * @param name
     * @param sex
     * @return 修改寝室楼信息
     */
    @RequestMapping("/Edit")
    public Result Edit(@RequestParam("id")Integer id,@RequestParam("name")String name,@RequestParam("sex")String sex){
        Builder builder = builderService.getOne(new QueryWrapper<Builder>().eq("lid",id));
        builder.setSex(sex);
        builder.setBuildName(name);
        boolean flag = builderService.updateById(builder);
        if (flag){
            return Result.success(200,"ok",null);
        }else {
            return Result.fail(401,"error",null);
        }
    }

    /**
     *
     * @return 寝室楼管理地图上现实的数据
     */
    @RequestMapping("/getMaplist")
    public Object getMaplist() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("type", "FeatureCollection");
        JSONArray jsonArray = new JSONArray();
        jsonObject.set("features", jsonArray);
        for (int i = 1; i <= 3; i++) {
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.set("type", "Feature");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.set("name", GaoDeLocationTemp.map.get(i).getName());
            JSONArray jsonArrays1 = new JSONArray();
            jsonArrays1.put(124.370173);
            jsonArrays1.put(40.18339);
            JSONArray jsonArrayS2 = new JSONArray();
            jsonArrayS2.put(100000);
            jsonArrayS2.put(330000);
            jsonArrayS2.put(330100);
            JSONArray jsonArrays3 = new JSONArray();
            jsonArrays3.put(124.370173);
            jsonArrays3.put(40.18339);
            jsonObject1.set("center",jsonArrays1);
            jsonObject1.set("centroid", jsonArrays3);
            jsonObject1.set("childrenNum", 0);
            jsonObject1.set("level", "district");
            JSONObject jsonObjects2 =  new JSONObject(null);
            jsonObjects2.set("adcode",GaoDeLocationTemp.map.get(i).getLid());
            jsonObject1.set("adcode",GaoDeLocationTemp.map.get(i).getLid());
            jsonObject1.set("parent", jsonObjects2);
            jsonObject1.set("subFeatureIndex", 0);
            jsonObject1.set("acroutes", jsonArrayS2);
            jsonObject3.set("properties", jsonObject1);
            jsonArray.put(jsonObject3);
            /*************************************************/
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.set("type", "MultiPolygon");
            JSONArray jsonArray1 = new JSONArray();
            JSONArray jsonArray2 = new JSONArray();
            jsonArray1.put(jsonArray2);
            jsonArray2.put(StrtoLocal(GaoDeLocationTemp.map.get(i).getLocaltion()));//这里获取转换后的经纬度
            jsonObject2.set("coordinates", jsonArray1);
            jsonObject3.set("geometry", jsonObject2);
        }
        return jsonObject;
    }


}